package com.sgb.knowledgeshare.view.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import com.sgb.knowledgeshare.R;
import com.sgb.knowledgeshare.databinding.FragmentShareRecommendBinding;
import com.sgb.knowledgeshare.entity.UserBean;
import com.sgb.knowledgeshare.utils.PageChangeEvent;
import com.sgb.knowledgeshare.utils.RxBus;
import com.sgb.knowledgeshare.view.activity.LabelDetailsActivity;
import com.sgb.knowledgeshare.view.adapter.RecommendMenuAdapter;
import com.sgb.knowledgeshare.viewmodel.RecommendModel;
import com.sgb.knowledgeshare.weight.AlivcVideoListView;
import com.sgb.knowledgeshare.weight.AlivcVideoPlayView;
import com.sgb.knowledgeshare.weight.CenterLayoutManager;
import com.sgb.knowledgeshare.weight.CommentDialog;
import com.sgb.knowledgeshare.weight.ControllerView;
import com.sgb.knowledgeshare.weight.RightDrawerLayout;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.model.entity.VideoBean;
import com.sgb.knowledgeshare.utils.OnVideoControllerListener;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.knowledgeshare.weight.ShareDialog;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.entity.VideoListEntity;

import java.util.ArrayList;
import java.util.List;

public class RecommendFragment extends AppLazyFragment {
    RecommendModel viewmode;
    private FragmentShareRecommendBinding binding;
    private int page;
    private boolean isLoadMore = false;
    /**
     * 播放列表信息
     */
    private List<VideoBean> adapterList;
    /**
     * 正在播放视频的数据信息
     */
    private VideoBean videobean;
    /**
     * 侧边栏的page
     */
    private int pageNum;
    private String userNo;
    /**
     * 侧边栏数据展示的adapter
     */
    private RecommendMenuAdapter mMenuAdapter;
    private CenterLayoutManager mCenterLayoutManager;
    /**
     * 正在播放视频的位置
     */
    private int VideoPlayIndex = -1;
    /**
     * 打开侧边栏是记录的位置
     */
    private int curPlayPos;

    /**
     * 记录保存打开侧边栏之前的数据信息
     */
    private List<VideoBean> mOriData = new ArrayList<>();
    private int pages;
    private int pages1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_share_recommend, container, false);
        viewmode = new ViewModelProvider(this).get(RecommendModel.class);
        viewmode.setActivity(RecommendFragment.this);
        View decor = getActivity().getWindow().getDecorView();
        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        binding.videoPlayDetailView.setShowComment(false);
        return binding.getRoot();
    }

    @Override
    protected void initView() {
        binding.videoPlayDetailView.setOnRefreshDataListener(new AlivcVideoListView.OnRefreshDataListener() {
            @Override
            public void onRefresh() {
                if (binding.drawerLayout.isDrawerClosed()) {
                    initdata();
                } else {
                    if (videobean != null) {
                        userNo = videobean.getCreateUser();
                        pageNum = 1;
                        viewmode.getMyVodList(pageNum, videobean.getCreateUser(), videobean.getVideoId());
                    }
                }
            }

            @Override
            public void onLoadMore() {
                isLoadMore = true;
                if (binding.drawerLayout.isDrawerClosed()) {
                    page = page == pages1 ?  1: page + 1;

                    viewmode.getFirstPageList(page + "", "0");
                } else {
                    pageNum++;
                    if (pageNum <= pages) {
                        if (videobean != null) {
                            userNo = videobean.getCreateUser();
                            viewmode.getMyVodList(pageNum, videobean.getCreateUser(), videobean.getVideoId());
                        }
                    }
                }
            }
        });
        binding.videoPlayDetailView.setCallback(new AlivcVideoPlayView.UserVideoCallback() {
            @Override
            public void UserVideoController(ControllerView controller, VideoBean videoBean) {
                //视频右下角按钮点击事件处理
                likeShareEvent(controller);
            }

            @Override
            public void UserVideoLike(VideoBean bean, ControllerView controller) {
                //点赞
                viewmode.setLike(bean.getVideoId() + "");
                setShuangJiDianZan(bean, controller);
            }

            @Override
            public void VideoInfo(int pos, VideoBean video) {
                if (!binding.drawerLayout.isDrawerClosed()) {
                    mMenuAdapter.setCurPos(pos);
                }
                VideoPlayIndex = pos;
                videobean = video;
                RxBus.getDefault().post(new UserBean(video.getCreateUser()));
                //添加播放次数
                viewmode.getplayVideo(video.getVideoId());
            }
        });
        mMenuAdapter = new RecommendMenuAdapter(getContext(), null);
        mMenuAdapter.setItemSelect(true);
        binding.menuRecycler.setHasFixedSize(false);
        mCenterLayoutManager = new CenterLayoutManager(getContext());
        binding.menuRecycler.setLayoutManager(mCenterLayoutManager);
        binding.menuRecycler.setAdapter(mMenuAdapter);
        mMenuAdapter.setOnItemClick(new AdapterOnItemClick<VideoBean>() {
            @Override
            public void onItemClick(VideoBean recordsBean, int position) {
                binding.videoPlayDetailView.refreshVideoList(mMenuAdapter.getDatas(), position);
            }
        });
        binding.drawerLayout.addDrawerListener(new RightDrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
                boolean scroll = slideOffset >= 1.0f || slideOffset <= 0.0f;
                binding.videoPlayDetailView.onCanVerticalScroll(scroll);
                if (getParentFragment() != null) {
                    if (!TextUtils.isEmpty(videobean.getCreateUser())) {
                        ((ShareMianFragment) getParentFragment()).updateBottomViews(slideOffset, videobean.getCreateUser());
                    }
                }
            }

            @Override
            public void onDrawerOpened(@NonNull View drawerView) {
                if (mMenuAdapter != null) {
                    mMenuAdapter.setDatas(new ArrayList<>());
                    mMenuAdapter.notifyDataSetChanged();
                }
                curPlayPos = VideoPlayIndex;
                pageNum = 1;
                viewmode.getMyVodList(pageNum, videobean.getCreateUser(), videobean.getVideoId());
            }

            @Override
            public void onDrawerClosed(@NonNull View drawerView) {
                binding.videoPlayDetailView.setShowUser(true);
                //关闭侧边栏，类表数据定位到打开侧边栏数据位置
                if (mOriData != null && mMenuAdapter.getDatas().size() > 0) {
                    VideoBean videoBean = mMenuAdapter.getDatas().get(mMenuAdapter.getCurPos());
                    mOriData.set(curPlayPos, videoBean);
                }
                binding.videoPlayDetailView.refreshVideoList(mOriData, curPlayPos);
                adapterList = binding.videoPlayDetailView.getAdapterList();
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
    }

    private void initdata() {
        isLoadMore = false;
        page = 1;
        viewmode.getFirstPageList(page + "", "0");
    }

    @Override
    public void onVisible() {
        super.onVisible();
        if (binding != null) {
            binding.videoPlayDetailView.onResume();
        }
    }

    @Override
    protected void onLazyLoad() {
        initdata();
        binding.videoPlayDetailView.onResume();
    }

    @Override
    public void onInvisible() {
        super.onInvisible();
        if (binding != null) {
            binding.videoPlayDetailView.onPause();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (binding != null) {
            binding.videoPlayDetailView.onPause();
        }
    }

    @Override
    public void onDestroyView() {
        binding.videoPlayDetailView.onDestroy();
        super.onDestroyView();
    }


    public void setListVideo(VideoListEntity data) {
        pages1 = data.getPages();
        List<VideoBean> records = data.getRecords();
        if (null == records) {
            return;
        }
        if (isLoadMore) {
            if (records.size() > 0) {
                binding.videoPlayDetailView.addMoreData(records);
            } else {
                page = 1;
                viewmode.getFirstPageList(page + "", "0");
            }
        } else {
            if (records.size() > 0) {
                binding.videoPlayDetailView.refreshVideoList(records);
            } else {
                binding.videoPlayDetailView.loadFailure();
            }
        }
        adapterList = binding.videoPlayDetailView.getAdapterList();
    }

    private void likeShareEvent(ControllerView controller) {
        controller.setListener(new OnVideoControllerListener() {
            //点赞
            @Override
            public void onLikeClick(VideoBean data) {
                viewmode.setLike(data.getVideoId() + "");
                setDianZan(data, controller);
            }

            //点击分享的事件处理
            @Override
            public void onShareClick(VideoBean videoData) {
                new ShareDialog(getActivity(), 1, videoData).setOnDeleteVideo(new ShareDialog.OnDeleteVideo() {
                    @Override
                    public void OnDeleteVideoData(int Id) {
                        DeleteVideo(Id);
                    }
                });
            }

            // 点击头像下面的+号事件处理
            @Override
            public void onFocusClick(VideoBean videoData) {
                if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "").equals(videoData.getCreateUser())) {
                    MToast.showToast(getActivity(), "不能关注自己的视频");
                } else {
                    viewmode.getFens(videoData.getCreateUser());
                    setGuanzhu(videoData, controller);
                }
            }

            // 点击头像的事件处理
            @Override
            public void onHeadClick(VideoBean videoData) {
                RxBus.getDefault().post(new PageChangeEvent(1));
            }

            //评论
            @Override
            public void onCommentClick(VideoBean videoData) {
                new CommentDialog(getActivity(), videoData, "0", 1, 1).setonDialog(new CommentDialog.HiedDialog() {
                    @Override
                    public void onhiedDialog() {
                        viewmode.getCommentNum(videoData, controller);
                    }
                });
            }
            //实现直评论功能
            @Override
            public void onCommentSend(VideoBean videoBean) {

            }
            //点击标签跳转到标签
            @Override
            public void onLabelClickListener(VideoBean videoData) {
                LabelDetailsActivity.start(getActivity(),videoData.getLabelName(),videoData.getLabelNo());
            }
        });
    }


    //    删除视频的操作
    private void DeleteVideo(int id) {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        tv_message.setText("您的作品将被永久删除，无法找回。确认删除？");
        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除视频的操作逻辑
                roundCornerDialog.dismiss();
                viewmode.deleteMyVideo(id);
            }
        });
        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    private void setShuangJiDianZan(VideoBean bean, ControllerView controller) {
        if (bean.isLiked()) {
            int laudCountd = bean.getLaudCount();
            if (laudCountd > 0) {
                laudCountd--;
            }
            bean.setLaudCount(laudCountd);
        } else {
            int laudCountd = bean.getLaudCount();
            laudCountd++;
            bean.setLaudCount(laudCountd);
        }
        bean.setLiked(!bean.isLiked());
        controller.setVideoData(bean, getContext(),false);
        controller.like();
    }

    private void setGuanzhu(VideoBean videoData, ControllerView controller) {
        if (videoData.getIsFollow() == 1) {//为关注
            videoData.setIsFollow(0);
        } else {//没有关注
            videoData.setIsFollow(1);
        }
        controller.setVideoData(videoData, getContext(),false);
    }

    private void setDianZan(VideoBean data, ControllerView controller) {
        if (data != null) {
            if (data.isLiked()) {
                int laudCountq = data.getLaudCount();
                if (laudCountq != 0) {
                    laudCountq--;
                }
                data.setLiked(false);
                data.setLaudCount(laudCountq);
            } else {
                int laudCountd = data.getLaudCount();
                laudCountd++;
                data.setLaudCount(laudCountd);
                data.setLiked(true);
            }
            controller.setVideoData(data, getContext(),false);
            controller.like();
        }
    }

    //刷新数据
    public void setDataList() {
        initdata();
    }

    public void setCommentNum(VideoBean videoData, ControllerView controllerView) {
        controllerView.setVideoData(videoData, getContext(),false);
    }

    public void setUserVideoListData(int total, VideoListEntity data) {
        pages = data.getPages();
        List<VideoBean> records = data.getRecords();
        if (null == records) {
            return;
        }
        if (getParentFragment() != null) {
            ((ShareMianFragment) getParentFragment()).updataUserInfo(videobean, total);
        }
        if (pageNum == 1) {
            if (records.size() > 0) {
                mMenuAdapter.setDatas(new ArrayList<>());
                mOriData.clear();
                mOriData.addAll(adapterList);
                mMenuAdapter.setDatas(records);
                if (mMenuAdapter != null && mMenuAdapter.getDatas().size() > 0) {
                    binding.videoPlayDetailView.setShowUser(false);
                    mMenuAdapter.setCurPos(0);
                    binding.videoPlayDetailView.refreshVideoList(mMenuAdapter.getDatas(), 0);
                }
            }
        } else {
            if (records.size() > 0) {
                mMenuAdapter.addDatas(records);
                binding.videoPlayDetailView.addMoreData(records);
            } else {
                MToast.showToast(getContext(), "没有视频啦");
            }
        }
    }

    public void setListVideo() {

    }
}
